const express = require('express');
const cors = require('cors');
const axios = require('axios');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3001;
const TRANSLATE_ENGINE_URL = process.env.TRANSLATE_ENGINE_URL;

// 中间件
app.use(cors());
app.use(express.json());

// 健康检查接口
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', message: '翻译服务运行正常' });
});

// 单个文本翻译接口
app.post('/api/translate', async (req, res) => {
  try {
    const { text, source, target } = req.body;
    
    if (!text || !target) {
      return res.status(400).json({ error: '缺少必要参数' });
    }
    
    console.log(`翻译请求: ${source || 'auto'} -> ${target}, 文本: ${text.substring(0, 30)}...`);
    
    // 调用翻译引擎
    const response = await axios.post(TRANSLATE_ENGINE_URL, {
      q: text,
      source: source || 'auto',
      target,
      format: 'text'
    });
    
    res.json({ 
      translatedText: response.data.translatedText,
      originalText: text,
      source: response.data.detectedLanguage?.language || source,
      target
    });
  } catch (error) {
    console.error('翻译错误:', error.message);
    res.status(500).json({ 
      error: '翻译失败', 
      message: error.message,
      details: error.response?.data || '未知错误'
    });
  }
});

// 批量翻译接口
app.post('/api/translate-batch', async (req, res) => {
  try {
    const { texts, source, target } = req.body;
    
    if (!Array.isArray(texts) || !target) {
      return res.status(400).json({ error: '缺少必要参数或格式错误' });
    }
    
    console.log(`批量翻译请求: ${source || 'auto'} -> ${target}, 文本数量: ${texts.length}`);
    
    // 批量翻译处理
    const promises = texts.map(text => 
      axios.post(TRANSLATE_ENGINE_URL, {
        q: text,
        source: source || 'auto',
        target,
        format: 'text'
      })
    );
    
    const results = await Promise.all(promises);
    const translations = results.map((result, index) => ({
      key: texts[index],
      translation: result.data.translatedText,
      source: result.data.detectedLanguage?.language || source
    }));
    
    res.json({ translations });
  } catch (error) {
    console.error('批量翻译错误:', error.message);
    res.status(500).json({ 
      error: '批量翻译失败', 
      message: error.message,
      details: error.response?.data || '未知错误'
    });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`翻译服务器运行在端口 ${PORT}`);
  console.log(`翻译引擎URL: ${TRANSLATE_ENGINE_URL}`);
});